/* -*- mode: c++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- */

#ifndef _FOREACH_H_
#define _FOREACH_H_

template <typename C>
struct _ForeachHelper {
    typename C::iterator it, end;
    _ForeachHelper (C& c) : it(c.begin()), end(c.end())
    {
    }
};

#define FOREACH_HELPER(line)            FOREACH_HELPER_(line)

#define FOREACH_HELPER_(line)           __foreach_helper_ ## line

#define FOREACH_CONTINUE                __foreach_continue

#define FOREACH(var, cont)                                              \
    _ForeachHelper<__typeof__(cont)> FOREACH_HELPER(__LINE__)(cont);    \
    for (bool FOREACH_CONTINUE = true;                                  \
         (FOREACH_CONTINUE                                              \
          && (FOREACH_HELPER(__LINE__).it                               \
              != FOREACH_HELPER(__LINE__).end));                        \
         ++FOREACH_HELPER(__LINE__).it)                                 \
        if (FOREACH_CONTINUE = false) {} else                           \
            for (var = *FOREACH_HELPER(__LINE__).it;                    \
                 !FOREACH_CONTINUE;                                     \
                 FOREACH_CONTINUE = true)

#endif /* _FOREACH_H_ */
